<template>
  <view>
    <view class="address-section">
      <text>收货地址</text>
      <scroll-view class="scroll-view" scroll-y>
        <scroll-item 
          v-for="(item, index) in deliveryList" 
          :key="index" 
          class="delivery-item"
        >
          <!-- 地址与联系人信息 -->
          <view class="delivery-text">
            <text>{{ item.address }}</text>
            <text>{{ item.contactName }}/{{ item.contactPhone }}</text>
          </view>
         <button  
           @click="selectAddress(index)"  
           :class="['delivery-but', { 'selected': selectDeliveryId === index }]">
           <uni-icons type="checkmarkempty" size="20"></uni-icons>
         </button>
        </scroll-item>
      </scroll-view>
    </view>

    <view class="order-section">
      <text>订单信息</text>
      <view class="product-info">
        <image :src="getPrimaryImageUrl(productList.images)" mode="aspectFill"></image>
        <text>{{ productList.productName }}</text>
      </view>
	  <scroll-view class="product-scroll">
       <scroll-item v-for="(sku, index) in orderSkus" :key="index" class="order-item">
        <text>{{ sku.skuName }}</text>
        <text>￥{{ sku.price }} x {{ sku.quantity }}</text>
       </scroll-item>
	  </scroll-view>
    </view>

    <view class="total-section">
      <text>合计金额：￥{{ calculateTotal() }}</text>
    </view>
    <button @click="submitOrder">提交订单</button>
  </view>
</template>


<script>
import { getDelivery } from '../../../api/delivery/delivery.js';
import { insertOrder } from '../../../api/order/order.js';
export default {
  data() {
    return {
      orderSkus: [],       // 存储从上一个页面传递的 SKU 数据
      deliveryList: [],    // 存储收货地址信息
      userId: null,        // 用户ID
      productList: {},     // 存储传递的 productList 数据
	  selectDeliveryId:0
    };
  },
  onLoad(options) {
    // 解析传递的参数
    if (options.orderData) {
      try {
        this.orderSkus = JSON.parse(decodeURIComponent(options.orderData));
      } catch (error) {
        console.error('订单数据解析失败:', error);
      }
    }
  
    // 获取 productList 参数
    if (options.productList) {
      try {
        this.productList = JSON.parse(decodeURIComponent(options.productList));
      } catch (error) {
        console.error('productList 数据解析失败:', error);
      }
    }
  // 获取用户信息
  if (!this.userId) {
    this.$store
      .dispatch('GetInfo')
      .then(() => {
        this.userId = this.$store.state.user.userId;
        console.log("用户ID:", this.userId);
        this.getDelivery();  // 获取配送信息
      })
      .catch((error) => {
        console.error("获取用户信息失败:", error);
      });
  }
   
  },

  methods: {
    // 获取配送信息
    async getDelivery() {
      try {
        this.deliveryList = await getDelivery(this.userId);
      } catch (error) {
        console.error('获取配送信息失败:', error);
      }
    },
    calculateTotal() {
      // 计算合计金额
      return this.orderSkus
        .reduce((total, sku) => total + sku.price * sku.quantity, 0)
        .toFixed(2);
    },
    selectAddress(index) {
      this.selectDeliveryId=index;
    },
	//获取商品主图
	
	getPrimaryImageUrl(images) {
	   if (!images || images.length === 0) {
	     // 返回默认动态图片路径
	     return '/static/home/dj.jpg'; // 默认图片的 URL
	   }
	  
	   const primaryImage = images.find(image => image.isPrimary);
	   // 返回主图 URL 或第一张图片的 URL，如果都没有，则返回默认图片
	   return primaryImage?.imageUrl || images[0]?.imageUrl || '/static/home/dj.jpg';
	 },
	
async submitOrder() {
      // 准备订单数据
      const orderPayload = {
        userId: this.userId,
        deliveryId: this.deliveryList[this. selectDeliveryId].deliveryId,
        productId: this.productList.productId,
        orderSkus: this.orderSkus.map(sku => ({
		  skuName:sku.skuName,
          skuId: sku.skuId,
          quantity: sku.quantity,
          unitPrice: sku.price,
          totalPrice: (sku.price * sku.quantity).toFixed(2),
        })),
        totalAmount: this.calculateTotal(),
        orderStatus: '0', // 初始状态：待支付
      };

      try {
        await insertOrder(orderPayload);
        wx.showToast({
             title: '订单提交成功',
             icon: 'loading',
             duration: 1000, // 显示 2 秒
			
           });
       
           // 延迟 2 秒后跳转到支付页面
           setTimeout(() => {
             uni.redirectTo({
               url: `/pages/product/confirm/pay`,
             });
           }, 1000);
      } catch (error) {
        wx.showToast({
          title: '订单提交失败',
          icon: 'error',
        });
        console.error('提交订单失败:', error);
      }
    },

  },
};
</script>

<style lang="scss">
/* 公共样式 */
view {
  display: flex;
  flex-direction: column;
  padding: 10px;
  background-color: #ffffff;
}

/* 收货地址区 */
.address-section {
  height: 250px; /* 设置滚动视图的固定高度 */
  background-color: #ffaa7f;
  margin-bottom: 16px;
  padding: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.scroll-view {
  max-height: 100%;
  overflow-y: scroll;
}

/* 单个地址项 */
.delivery-item {
  display: flex;
  justify-content: space-between; /* 左右两端对齐 */
  align-items: center; /* 垂直居中 */
  padding: 8px 0;
  border-bottom: 1px solid #eee;
}

.delivery-item:last-child {
  border-bottom: none; /* 最后一项去掉边框 */
}

.delivery-text {
  display: flex;
  flex-direction: column; /* 地址与联系人信息上下排列 */
  flex: 1; /* 占据剩余宽度 */
}

.delivery-text text:first-child {
  font-size: 16px;
  color: #333;
  margin-bottom: 4px;
  word-wrap: break-word; /* 长地址自动换行 */
}

.delivery-text text:last-child {
  font-size: 14px;
  color: #666;
}

/* 按钮基础样式 */
.delivery-but {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border: none;
  background: none;
  margin-left: 8px; /* 与文本部分保持间距 */
  color: #666; /* 默认颜色 */
  transition: color 0.3s ease, background-color 0.3s ease; /* 添加过渡效果 */
}

/* 按钮选中状态 */
.delivery-but.selected {
  color: #fff; /* 选中后字体颜色 */
  background-color: #00aa00; /* 选中后的背景色 */
}
/* 订单信息区 */
.order-section {

  background-color: #ffaa7f;
  margin-bottom: 16px;
  padding: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.product-info {
  display: flex;
 align-items: center;
  margin-bottom: 16px;
}

.product-info image {
  width: 80px;
  height: 80px;
  margin-right: 16px;
  border-radius: 8px;
  object-fit: cover;
  background-color: #eee;
}

.product-info text {
  flex: 1;
  font-size: 16px;
  color: #333;
}
.product-scroll {
  height: 120px;/* 固定高度 */
  overflow-y: auto; /* 开启滚动 */
  border-top: 1px solid #eee;
  border-bottom: 1px solid #eee;
  padding: 8px 0;
}

.order-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;
  color: #333;
}

.order-item text {
  flex: 1;
}

.order-item:last-child {
  margin-bottom: 0;
}

/* 合计金额 */
.total-section {
  background-color: #ffffff;
  margin-bottom: 16px;
  padding: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  font-size: 16px;
  color: #333;
  text-align: right;
}
.total-section text{
	color: #ff0000;
}
/* 按钮 */
button {
  width: 100%;
  height: 48px;
  background-color: #00aa00;
  color: #fff;
  font-size: 16px;
  text-align: center;
  border: none;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

button:active {
  background-color: #e64a19;
}

</style>
